package com.cn.demo.config;

import com.cn.demo.util.CommonConstants;
import org.redisson.api.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀过用户哈希表，10秒钟过期
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/11/15 14:34
 * @projectName test
 */
@Component
public class SeckillUserMapCache implements InitializingBean {

    @Autowired
    private RedissonClient redisson;
    private RMapCache<String, String> seckillUserMap;


    @Override
    public void afterPropertiesSet() throws Exception {
        if (seckillUserMap == null) {
            seckillUserMap = redisson.getMapCache("seckillUserMap");
        }
        Assert.notNull(seckillUserMap, "秒杀用户哈希表初始化失败, seckillUserMap is null");
    }

    /**
     * 清空数据
     * @author: wangjf
     * @createTime: 2019/11/18 10:49
     * @param
     * @return void
     */
    public void clear(){
        seckillUserMap.clear();
    }

    /**
     * 获取KEY
     *
     * @param userId
     * @return java.lang.String
     * @author: wangjf
     * @createTime: 2019/11/15 14:50
     */
    public String get(String userId) {
        return seckillUserMap.get(userId);
    }

    /**
     * PUTkey,10秒过期
     *
     * @param userId
     * @return void
     * @author: wangjf
     * @createTime: 2019/11/15 14:50
     */
    public void put(String userId) {
        seckillUserMap.put(userId, userId, CommonConstants.SECKILL_USER_TTL, TimeUnit.SECONDS);
    }

    /**
     * key存在则返回true，否则返回false
     *
     * @param userId
     * @return java.lang.Boolean
     * @author: wangjf
     * @createTime: 2019/11/15 14:50
     */
    public Boolean existKey(String userId) {
        String value = seckillUserMap.get(userId);
        if (value == null) {
            return false;
        }
        return true;
    }
}
